package com.xg.util.export;

import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;

import java.lang.reflect.Field;
import java.util.List;

public class CustomColumnWidthHandler implements CellWriteHandler {

    // 存储实体类字段（与表头列索引顺序一致）
    private final List<Field> entityFields;

    // 构造方法：传入实体类字段列表
    public CustomColumnWidthHandler(List<Field> entityFields) {
        this.entityFields = entityFields;
    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead && relativeRowIndex == 2) { // 只在三级表头的最后一行（字段名行）设置列宽
            int columnIndex = cell.getColumnIndex(); // 列索引（0开始）
            // 校验列索引是否在字段列表范围内
            if (columnIndex < entityFields.size()) {
                Field field = entityFields.get(columnIndex); // 列索引与字段列表顺序对应
                ColumnWidth columnWidth = field.getAnnotation(ColumnWidth.class);
                if (columnWidth != null) {
                    Sheet sheet = writeSheetHolder.getSheet();
                    // 设置列宽（Excel单位：1/256个字符宽度）
                    sheet.setColumnWidth(columnIndex, columnWidth.value() * 256);
                }
            }
        }
    }

    // 其他方法保持空实现...
    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 org.apache.poi.ss.usermodel.Row row, Head head, Integer columnIndex,
                                 Integer relativeRowIndex, Boolean isHead) {}

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                       com.alibaba.excel.metadata.data.WriteCellData<?> cellData, Cell cell,
                                       Head head, Integer relativeRowIndex, Boolean isHead) {}

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<com.alibaba.excel.metadata.data.WriteCellData<?>> cellDataList,
                                 Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
}